//
//  MTContactVC.swift
//  WeFamily
//
//  Created by 崔世强 on 2020/6/17.
//  Copyright © 2020 Meak Tsui. All rights reserved.
//

import UIKit
import Kingfisher

class MTContactVC: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    
    var contactList = [ChatContact]()
    let collation = UILocalizedIndexedCollation.current()
    var sectionsArray: [[ChatContact]] = [[ChatContact]]()
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        self.title = NSLocalizedString("通讯录", comment: "通讯录")
        self.tabBarItem.image = UIImage(named: "tstAddressBook_Default")
        if #available(iOS 13, *) {
            self.tabBarItem.image = UIImage(systemName: "person.2.square.stack")
        }
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    
    lazy var tableFootView:UIView = {
        let tableFootview = UIView(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 55))
        return tableFootview
    }()
    
    lazy var bottomLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 18)
        label.textColor = UIColor.lightGray
        self.tableFootView.addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        
        label.topAnchor.constraint(equalTo: self.tableFootView.topAnchor).isActive = true
        label.bottomAnchor.constraint(equalTo: self.tableFootView.bottomAnchor).isActive = true
        label.leadingAnchor.constraint(equalTo: self.tableFootView.leadingAnchor).isActive = true
        label.trailingAnchor.constraint(equalTo: self.tableFootView.trailingAnchor).isActive = true
        return label
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.tableFooterView = tableFootView
        self.tableView.register(ContactCell.self, forCellReuseIdentifier: ContactCell.contactCellId)
        loadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
    }
    
    let service = ContactService()
    
    func loadData() {
        DispatchQueue.global().async {
            self.contactList = self.service.getContactList()
            if self.contactList.count > 0 {
                self.setSection()
                DispatchQueue.main.async {
                    self.bottomLabel.text = "\(self.contactList.count)位联系人"
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    func setSection(){
        //        self.collation = UILocalizedIndexedCollation.current()
        let sectionTitlesCount = self.collation.sectionTitles.count
        print(sectionTitlesCount)
        //临时数据，存放section对应的userObjs数组数据
        var newSectionsArray = [[ChatContact]]()
        
        //设置sections数组初始化：元素包含userObjs数据的空数据
        for _ in 0 ..< sectionTitlesCount {
            let array = [ChatContact]()
            newSectionsArray.append(array)
        }
        
        //将用户数据进行分类，存储到对应的sesion数组中
        
        for contact in contactList {
            //根据timezone的localename，获得对应的的section number
            let sectionNumber = self.collation.section(for: contact, collationStringSelector: #selector(getter: ChatContact.displayName))
            _ = self.collation.sectionTitles[sectionNumber]
            //            if !indexArray.contains(headerString) {
            //                indexArray.append(headerString)
            //            }
            //
            //获得section的数组
            var sectionBeans = newSectionsArray[sectionNumber]
            
            //添加内容到section中
            sectionBeans.append(contact)
            
            // swift 数组是值类型，要重新赋值
            newSectionsArray[sectionNumber] = sectionBeans
        }
        
        //排序，对每个已经分类的数组中的数据进行排序，如果仅仅只是分类的话可以不用这步
        for i in 0 ..< sectionTitlesCount {
            let beansArrayForSection = newSectionsArray[i]
            //获得排序结果
            let sortedBeansArrayForSection = collation.sortedArray(from: beansArrayForSection, collationStringSelector:  #selector(getter: ChatContact.displayName))
            //替换原来数组
            newSectionsArray[i] = sortedBeansArrayForSection as! [ChatContact]
            
        }
        
        sectionsArray = newSectionsArray
    }

}

extension MTContactVC: UITableViewDataSource,UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if sectionsArray.count == 0 {
            return 0
        }
        let beanInSection = sectionsArray[section]
        return beanInSection.count
    }
    
//    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        let user = sectionsArray[indexPath.section][indexPath.row]
//        let cell = UITableViewCell()
//        cell.accessoryType = .disclosureIndicator
//        cell.imageView?.image = UIImage(named: "defaultAvatar"),options: [.processor(CryptorProcessor())]
//        cell.textLabel?.text = user.displayName
//        return cell
//    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: ContactCell.contactCellId, for: indexPath) as! ContactCell
        let chatContact = sectionsArray[indexPath.section][indexPath.row]
        
        cell.selectionStyle = .none
        cell.nameLabel.text = chatContact.displayName
        cell.headimage.kf.setImage(with: KF.ImageResource(downloadURL: Common.avatarUrl(chatContact.avatar ?? "unknown")!), placeholder: UIImage.init(named:"defaultAvatar"),options: [.processor(CryptorProcessor())])
        cell.tagbutton.isHidden = true
        return cell
    }
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.collation.sectionTitles.count
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if sectionsArray.isEmpty {
            return nil
        }
        let beanInSection = sectionsArray[section]
        if beanInSection.isEmpty {
            return nil
        }
        return self.collation.sectionTitles[section]
    }
    
    //设置索引标题
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        var temparry = [String]()
        temparry.append("*")
        temparry += collation.sectionTitles
        return temparry
    }
    
    //关联搜索
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        return collation.section(forSectionIndexTitle: index)
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if sectionsArray.isEmpty {
            return 0
        }
        let beanInSection = sectionsArray[section]
        if beanInSection.isEmpty {
            return 0
        }
        return 23;
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        let session = sectionsArray[indexPath.section][indexPath.row]
        let chatvc = ChatVC()
        chatvc.title = session.displayName
        chatvc.chatType = ChatType.p2p
        chatvc.sessionServerId = session.userId
        chatvc.sessionName = session.displayName
        chatvc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(chatvc, animated: true)
    }
    
}
